import {login,fetchUserInfo} from "../services/user"
import storage from "../utils/storage";
import {routerRedux} from "dva/router"
const token = storage.getItem('token')
export default {
    namespace:"user",
    state:{
        info:{},
        token: token || '',
    },
    subscriptions: {
      init({dispatch}) {  // eslint-disable-line
        if (token) {
          dispatch({
            type: 'user/fetchUserInfo'
          })
        }
      },
      },
    
      effects: {
        *login({ payload }, { call, put }) {  // eslint-disable-line
          const tokenData = yield call(login, payload)
          storage.setItem('token', tokenData.token)
          yield put({
            type: 'changeState',
            payload: {
              token: tokenData.token
            }
          })
          yield call(login,payload)
          yield put({
            type:"fetchUserInfo"
          })
          yield put(
            routerRedux.push({
              pathname:"/questions/list"
            })
          )
        },
        *fetchUserInfo({ action }, { call, put }) {  // eslint-disable-line
          const info=yield call(fetchUserInfo)
          yield put({
            type: 'changeState',
            payload: {
              info: info.data
            }
          })
        },
      },
    
      reducers: {
        changeState(state, action) {
          return { ...state, ...action.payload };
        },
      },
}